<?php
// +----------------------------------------------------------------------
// | snake
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2022 http://baiyf.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: NickBai <1902822973@qq.com>
// +----------------------------------------------------------------------
namespace app\common\logic;

use app\common\model\Admin;
use gdbase\Auth;
use function PHPSTORM_META\type;
use think\Db;
use think\Log;

class ContentLogic extends BaseLogic
{
    public function _getCategorySelectData(array $where){
        $field[] = 'id AS id';
        $field[] = 'cat_name AS text';
        $field[] = 'parent_id';
        $where[] = ['delete_time','<',1];
        $dataList = db('Category')->where($where)->field(join(',',$field) )->select();
        return $dataList;
    }

    /**
     * 模型 扩展表 扩展列
     * @param $id
     */
    public function _getModelsExtendTableInfo($modelsId,$type){
        $extendTable = $this->_getModelsExtendTable($modelsId);

        if(empty($extendTable)){
            return [];
        }
        $fieldInfo = [];
        foreach ($extendTable as $item){
            $aorm = model($item['table_name']);
            switch ($type){
                case 'list':
                    $tmp = $aorm->getListFields();
                    break;
                case 'edit':
                    $tmp = $aorm->getEditFields();
                    break;
                case 'add':
                default:
                    $tmp = $aorm->getAddFields();
                    break;
            }

            foreach ($item['field'] as $value){
                if(array_key_exists($value,$tmp)){
                    $fieldInfo[$value] = $tmp[$value];
                }
            }
        }

        return $fieldInfo;
    }

    /**
     * 模型 扩展表
     * @param $id
     */
    public function _getModelsExtendTable($modelsId){
        $models = db('Models')->where('id',$modelsId)->find();
        if(empty($models)){
            return [];
        }

        $extendTable = json_decode($models['extend_table'],true);

        if(empty($extendTable)){
            return [];
        }

        return $extendTable;
    }

    /**
     * 获取扩展表的值
     * @param string $tableName 主表名称
     * @param integer $id 主表ID
     * @param int $modelsId 模型ID 不传的时候自动获取
     * @return array
     * @throws \Exception
     */
    public function _getExtendTableColumValue($tableName,$id,$modelsId = 0){
        if(empty($id)){
            exception('主表ID错误');
        }
        if(empty($modelsId)){
            $modelsId = db($tableName)->where('id',$id)->value('model_id');
        }

        if(empty($modelsId)){
            exception('模型错误');
        }

        $extendTable = $this->_getModelsExtendTable($modelsId);

        if(empty($extendTable)){
            return [];
        }
        $zhi = [];
        foreach ($extendTable as $item){
            // 2018.04.07 早上 优化 先取出整条数据 然后 再按列返回
            $tmp = db($item['table_name'])->where($item['pk'],$id)->find();
            if(empty($tmp)){
                // 如果为空赋值 空
                foreach ($item['field'] as $value){
                    $zhi[$value] = '';
                }
            }
            else{
                foreach ($item['field'] as $value){
                    $zhi[$value] = $tmp[$value];
                }
            }

        }

        return $zhi;
    }

    /**
     * 设置扩展表的值
     * @param string $tableName 主表名称
     * @param integer $id 主表ID
     * @param array $data 需要保存的数据
     * @param int $modelsId 模型ID 不传的时候自动获取
     * @return array|bool
     * @throws \Exception
     */
    public function _setExtendTableColumValue($tableName,$id,$data,$modelsId = 0){
        if(empty($id)){
            \think\facade\Log::error('setExtendTableColumValue 错误 传值 $tableName ' . $tableName
                . ' $id '.$id . ' $data ' . json_encode($data,256) . ' $modelsId ' . $modelsId);
            exception('主表ID错误');
        }
        if(empty($modelsId)){
            $modelsId = db($tableName)->where('id',$id)->value('model_id');
        }

        if(empty($modelsId)){
            exception('模型错误');
        }

        $extendTable = $this->_getModelsExtendTable($modelsId);

        if(empty($extendTable)){
            return [];
        }
        $chenggong = 0;
        $bLogic = new BaseLogic();
        foreach ($extendTable as $item){
            $data[$item['pk']] = $id;
            $jieguo = $bLogic->save($data,$item['table_name']);
            if($jieguo['err_code'] < 1){
                $chenggong++;
            }
        }

        return $chenggong == count($extendTable);
    }

    /**
     * 获取模型需要显示的列
     * @param string $tableName 当前操作的表名称
     * @param int $modelsId 对应的模型ID
     * @param string $type 类型 add 添加 ； edit 编辑
     * @return array
     * @throws \Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function _getModelsShowField($tableName,$modelsId,$type){
        $modelsModel = Db::name('Models')->where('id',$modelsId)->find();
        if(empty($modelsModel)){
            exception('获取模型错误，请检查 模型ID');
        }

        $showField = json_decode($modelsModel['show_field'],true);
        if(empty($showField)){
            exception('显示的列解析错误');
        }
        // 判断 显示列定义里面是否有要获取的类型
        if(!array_key_exists($type,$showField)){
            \think\facade\Log::error('getModelsShowField 方法 错误 未找到请求的类型 请求参数 ' . json_encode(func_get_args(),256));
            return [];
        }
        $orm = model($tableName);
        // 取出已经定义的列
        switch ($type){
            case 'list':
                $formFields = $orm->getListFields();
                break;
            case 'edit':
                $formFields = $orm->getEditFields();
                break;
            case 'add':
            default:
                $formFields = $orm->getAddFields();
                break;
        }

        // 取出扩展的列
        $extendField = $this->_getModelsExtendTableInfo($modelsId,$type);
        // 合并列
        $formFields = array_merge($formFields,$extendField);
        // 过滤列，判断如果为数组，进行替换
        foreach ($formFields as $key => $field){
            if(!array_key_exists($key,$showField[$type])){
                unset($formFields[$key]);
            }
            else{
                if(!empty($showField[$type][$key])){
                    // 2018.04.04 合并条件
                    $formFields[$key] = array_merge($formFields[$key],$showField[$type][$key]);
                }
            }
        }

        array_multisort(array_column($formFields,'sort'),SORT_ASC,$formFields);

        return $formFields;
    }

    /**
     * 获取 一条数据 包含扩展信息
     * 先用传入条件做搜索，然后反推出 $modelsId
     * @param string $tableName 表名
     * @param array $where 只能基于主表现有的列做条件
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getModelModelsByWhere($tableName,$where){
        $model = Db::name($tableName)->where($where)->find();
        if(empty($model)){
            return [];
        }
        //  判断 取回来的数据是否有 model_id 列 没有的话直接返回model 不再进行扩展查找
        if(!array_key_exists('model_id',$model)){
            return $model;
        }
        $ext = $this->_getExtendTableColumValue($tableName,$model['id'],$model['model_id']);
        $model = array_merge($model,$ext);

        return $model;
    }

    /**
     * 按模型获取分页
     * @param $modelId
     * @param array $where
     * @param int $pageIndex
     * @param int $pageSize
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function _getPagerByModelIdAndWhere($modelId,$where = array(),$pageIndex = 1,$pageSize = 10){
        $where[] = ['model_id','=',$modelId];

        if($pageIndex < 1){
            $pageIndex = 1;
        }

        $offset = ($pageIndex - 1) * $pageSize;

        return Db::name('Content')->where($where)->limit($offset, $pageSize)->select();
    }

    /**
     * 获取模型
     * @param $where
     * @param string $order
     * @param bool $cache
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function _getModelsByWhere($where,$order = '',$cache = false){
        return db('Models')->where($where)->order($order)->cache($cache)->find();
    }

    /**
     * @param $code
     * @param string $order
     * @param bool $cache
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function _getModelsByCode($code){
        $cacheKey = '_getModelsByCode';
        $modelsList = cache($cacheKey);
        if (empty($modelsList)) {
            $modelsList = Db::name('Models')->select();
            cache($cacheKey,$modelsList);
        }
        foreach ($modelsList as $item) {
            if ($item['code'] == $code) {
                return $item;
            }
        }
        return [];
    }
}